# -*- coding: utf-8 -*-
# #############################################################################
#
# OpenERP, Open Source Management Solution
#    Copyright (C) 2004-2010 Tiny SPRL (<http://tiny.be>).
#
#    This program is free software: you can redistribute it and/or modify
#    it under the terms of the GNU Affero General Public License as
#    published by the Free Software Foundation, either version 3 of the
#    License, or (at your option) any later version.
#
#    This program is distributed in the hope that it will be useful,
#    but WITHOUT ANY WARRANTY; without even the implied warranty of
#    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#    GNU Affero General Public License for more details.
#
#    You should have received a copy of the GNU Affero General Public License
#    along with this program.  If not, see <http://www.gnu.org/licenses/>.
#
##############################################################################

from osv import osv, fields
import calendar
from datetime import date
from datetime import datetime
from datetime import timedelta
import math
import time
# from babel.messages.catalog import Message


class product_product(osv.osv):
    _inherit = 'product.product'

    def _product_min_qty(self, cr, uid, ids, name, arg, context=None):
        res = {}
        orderpoint_obj = self.pool.get('stock.warehouse.orderpoint')
        for obj in self.browse(cr, uid, ids):
            qty = 0
            list = orderpoint_obj.search(cr, uid, [('product_id', '=', obj.id), ('active', '=', True)])
            if list:
                qty = orderpoint_obj.browse(cr, uid, list[0]) and orderpoint_obj.browse(cr, uid,
                                                                                        list[0]).product_min_qty or 0
            res[obj.id] = qty
        return res

    def _check_min_qty(self, cr, uid, ids, name, arg, context=None):
        #### co check khi  virtual_available < product_min_qty
        res = {}
        for obj in self.browse(cr, uid, ids, context=context):
            checked = False
            if obj.virtual_available < obj.product_min_qty:
                checked = True
            res[obj.id] = checked
        return res

    def _check_rule(self, cr, uid, ids, name, arg, context=None):
        #### co check khi co rule
        res = {}
        orderpoint_obj = self.pool.get('stock.warehouse.orderpoint')
        for obj in self.browse(cr, uid, ids, context=context):
            checked = False
            list = orderpoint_obj.search(cr, uid, [('product_id', '=', obj.id), ('active', '=', True)])
            if list:
                checked = True
            res[obj.id] = checked
        return res

    def _stock_search_check_min(self, cr, uid, obj, name, args, context=None):
        pro_obj = self.pool.get('product.product')
        list_pro = pro_obj.search(cr, uid, [])
        ids = []
        for pro in pro_obj.browse(cr, uid, list_pro):
            if pro.virtual_available < pro.product_min_qty:
                ids.append(pro.id)
        return [('id', 'in', ids)]

    def _stock_search_check_rule(self, cr, uid, obj, name, args, context=None):
        pro_obj = self.pool.get('product.product')
        orderpoint_obj = self.pool.get('stock.warehouse.orderpoint')
        list_pro = pro_obj.search(cr, uid, [])
        ids = []
        for pro in pro_obj.browse(cr, uid, list_pro):
            list = orderpoint_obj.search(cr, uid, [('product_id', '=', pro.id), ('active', '=', True)])
            if list:
                ids.append(pro.id)
        return [('id', 'in', ids)]

    _columns = {
        'product_min_qty': fields.function(_product_min_qty, method=True, type='float', string='Min Quantity'),
        'check_min_qty': fields.function(_check_min_qty, method=True, string='Check min qty',
                                         fnct_search=_stock_search_check_min, type='boolean'),
        'check_rule': fields.function(_check_rule, method=True, string='Check rule',
                                      fnct_search=_stock_search_check_rule, type='boolean'),
    }

    def action_send_mail_rule(self, cr, uid, ids, context=None):
        print 'run email'
        smtp_obj = self.pool.get('email.smtpclient')
        pro_obj = self.pool.get('product.product')
        email_obj = self.pool.get('send.email.user')
        subject_boj = self.pool.get('email.subject')
        message = '<tr><td><p>Product Name  </td> <td><p>    Procude Code</td> <td><p>    Virtual Stock</td> </tr>'
        list_mess = ''
        subject = ''

        list_sub = subject_boj.search(cr, uid, [])
        if list_sub:
            subject = subject_boj.browse(cr, uid, list_sub[-1]).name
        else:
            subject = 'Subject For Product Rule'

        list_smtp = smtp_obj.search(cr, uid, [('state', '=', 'confirm'),
                                              ('active', '=', True)])
        list_product = pro_obj.search(cr, uid, [], context=context)
        for pro in pro_obj.browse(cr, uid, list_product):
            if pro.check_min_qty == True and pro.check_rule == True:
                message += '<tr><td><p>%s</td> <td><p>    %s</td> <td><p>    %s</td> </tr>' % (
                    pro.name, pro.default_code, pro.virtual_available)

        list_user = email_obj.search(cr, uid, [('user_email', '!=', False)])
        for user in email_obj.browse(cr, uid, list_user):
            for id_smtp in list_smtp:
                #             to = 'quanvm00@gmail.com'
                #             message = '<pre>%s</pre>' % id_smtp
                to = user.user_email
                subject = subject
                list_mess = message
                smtp_obj.send_email(cr, uid, id_smtp, to, subject, list_mess)
        return True


product_product()


class stock_warehouse_orderpoint(osv.osv):
    _inherit = 'stock.warehouse.orderpoint'

    def _product_min_qty(self, cr, uid, ids, name, arg, context=None):
        res = {}
        date_now = datetime.today()
        for obj in self.browse(cr, uid, ids):
            qty_min = 0
            rule_lines = obj.rule_line
            if rule_lines:
                for rule in rule_lines:
                    date_from = rule.date_from
                    date_to = rule.date_to
                    qty = rule.qty_min
                    date_from = datetime.strptime(date_from, "%Y-%m-%d")
                    date_to = datetime.strptime(date_to, "%Y-%m-%d")
                    if date_now >= date_from and date_now <= date_to:
                        qty_min = qty
                res[obj.id] = qty_min
        return res

    def _product_max_qty(self, cr, uid, ids, name, arg, context=None):
        res = {}
        date_now = datetime.today()
        for obj in self.browse(cr, uid, ids):
            qty_max = 0
            rule_lines = obj.rule_line
            if rule_lines:
                for rule in rule_lines:
                    date_from = rule.date_from
                    date_to = rule.date_to
                    qty = rule.qty_max
                    date_from = datetime.strptime(date_from, "%Y-%m-%d")
                    date_to = datetime.strptime(date_to, "%Y-%m-%d")
                    if date_now >= date_from and date_now <= date_to:
                        qty_max = qty
                res[obj.id] = qty_max
        return res

    _columns = {
        'product_min_qty': fields.function(_product_min_qty, method=True, type='float', string='Min Quantity'),
        'product_max_qty': fields.function(_product_max_qty, method=True, type='float', string='Max Quantity'),
        'rule_line': fields.one2many('stock.warehouse.orderpoint.rule', 'rule_id', 'Rule Lines'),

    }


stock_warehouse_orderpoint()

# vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4:
